﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;

namespace blackhouse.mojoPortalExtend.Breadcrumbs {
    public class BreadcrumbsAccess {

        #region Fields

        private Page currentPage;
        private SortedList<int, Crumb> crumbs;

        #endregion

        #region Properties

        public bool UserSet {
            get {
                return this.Crumbs.Count > 0;
            }
        }

        private SortedList<int, Crumb> Crumbs {
        
            get {
                if (this.crumbs == null) {
                    if (this.currentPage.Items.Contains("Breadcrumbs"))
                        this.crumbs = this.currentPage.Items["Breadcrumbs"] as SortedList<int, Crumb>;
                    if (this.crumbs == null) {
                        this.crumbs = new SortedList<int, Crumb>();
                        this.currentPage.Items.Add("Breadcrumbs", this.crumbs);
                    }
                }
                return this.crumbs;
            }
        }

        #endregion

        #region Constructors

        public BreadcrumbsAccess() {
            HttpContext context = HttpContext.Current;
            if (context == null)
                throw new Exception("HttpContext jest pusty!");

            this.currentPage = context.Handler as Page;
            if (this.currentPage == null)
                throw new InvalidOperationException("BreadcrumbsAccess potrzebuje dostępu do aktualnej strony! Prawdopodobnie próbujesz utworzyć instancję klasy poza ASP.NET");
        }

        #endregion

        #region Methods

        public void AddCrumb(string name, string url) {
            this.Crumbs.Add(this.Crumbs.Count, new Crumb(url, name));
        }

        internal SortedList<int, Crumb> GetCrumbs() {
            return this.Crumbs;
        }

        #endregion

    }
}
